package net.oschina.esb.webmvc.exception;

import net.oschina.esb.core.AbstractSpringBootRegister;
import net.oschina.esb.util.ClassScanner;
import net.oschina.esb.webmvc.exception.handler.ExceptionViewResolver;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.lang.reflect.Modifier;
import java.util.Set;

/**
 * 注册全局异常处理器
 *
 * @author Arvin
 * @time 2017/12/6 9:15
 */
@Configuration
public class AutoWebmvcExceptionSpringBootRegister extends AbstractSpringBootRegister {

    /** 默认异常视图处理器包 */
    private static final String DEFAULT_EXCEPTION_VIEW_RESOLVER_PACKAGE = ExceptionViewResolver.class.getPackage().getName();

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, Environment environment, ApplicationContext applicationContext) {

        Set<Class<?>> clazzSet = ClassScanner.scan(ExceptionViewResolver.class, DEFAULT_EXCEPTION_VIEW_RESOLVER_PACKAGE);

        for (Class<?> clazz : clazzSet) {

            int mod = clazz.getModifiers();
            if (Modifier.isInterface(mod) || Modifier.isAbstract(mod)) {
                continue;
            }

            String beanName = clazz.getName();

            GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
            beanDefinition.setBeanClass(clazz);
            beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
            registry.registerBeanDefinition(beanName, beanDefinition);

            logger.info("注册 ExceptionViewResolver：[" + clazz.getName() + "]");
        }
    }
}
